//
//  HWLoginAndRegisterViewController.m
//  HappyWeekend
//
//  Created by lanou on 16/1/13.
//  Copyright © 2016年 com.mjykj.www. All rights reserved.
//

#import "HWLoginAndRegisterViewController.h"


@interface HWLoginAndRegisterViewController ()<UITextFieldDelegate>



@end

@implementation HWLoginAndRegisterViewController

- (void)viewDidLoad {
    _isLogin = NO;
    self.view.backgroundColor = [UIColor colorWithRed:235.0f / 255.0f green:235.0f / 255.0f blue:241.0f / 255.0f alpha:1];
    [super viewDidLoad];
    [self addView];
    [self addBar];
    [self creatSQL];
}
- (void)creatSQL{
    // 创建我们的数据库路径, 同时拼接数据库的名字
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"PKDataBase.db"];
    // 根据路径去创建一个数据库
    [HWFileMannager shareManager].db = [FMDatabase databaseWithPath:path];
    NSLog(@"%@",path);
    // 调用 open 方打开数据库 成功返回 yes 失败 no
    if ([[HWFileMannager shareManager].db open]) {
        NSLog(@"数据库打开成功");
    } else {
        NSLog(@"数据库打开失败");
    }
    [[HWFileMannager shareManager].db executeUpdate:@"CREATE TABLE PersonList (uID text,coverimg text, uname text, icon text, auth text)"];

}
- (void)addBar{
    self.navigationItem.title = @"登陆";
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:(UIBarButtonItemStylePlain) target:self action:@selector(leftItemClick:)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"注册" style:(UIBarButtonItemStylePlain) target:self action:@selector(rightItemClick:)];
    self.navigationItem.rightBarButtonItem = rightItem;

}
- (void)rightItemClick:(UIBarButtonItem *)sender{
    HWRegisterViewController *registerVC = [[HWRegisterViewController alloc] init];
    registerVC.titles = @"注册";

    [self.navigationController pushViewController:registerVC animated:YES];

}
- (void)leftItemClick:(UIBarButtonItem *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)addView{
    _userView = [[HWLoginView alloc] initWithFrame:CGRectMake(10, 114, kScreenWidth - 20, 2 * 20)];
    _userView.backgroundColor = [UIColor whiteColor];
    _userView.userLabel.text = @"邮 箱";
    _userView.userText.placeholder = @"请输入邮箱";
    _userView.userText.tag = 100;
    _userView.userText.delegate = self;
    [self.view addSubview:_userView];
    
    _passwordView = [[HWLoginView alloc] initWithFrame:CGRectMake(10, _userView.bottom + 20, kScreenWidth - 20, 2 * 20)];
    _passwordView.backgroundColor = [UIColor whiteColor];
    _passwordView.userLabel.text = @"密  码";
    _passwordView.userText.placeholder = @"请输入密码";
    _passwordView.userText.tag = 101;
    _passwordView.userText.secureTextEntry = YES;
    _passwordView.userText.delegate = self;
    [self.view addSubview:_passwordView];
    
    UIButton *loginButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    loginButton.frame = CGRectMake(10, _passwordView.bottom + 2 * 20, kScreenWidth - 20, 2 * 20);
    loginButton.backgroundColor = [UIColor colorWithRed:39.0f / 255.0f green:134.0f / 255.0f blue:34.0f / 255.0f alpha:1];
    [loginButton setTitle:@"登陆" forState:(UIControlStateNormal)];
    [loginButton setTitleColor:[UIColor whiteColor] forState:
     (UIControlStateNormal)];
    loginButton.layer.masksToBounds = YES;
    loginButton.layer.cornerRadius = 2;
    [loginButton addTarget:self action:@selector(loginButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:loginButton];
    
    UILabel *threeloginLabel = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth / 2 - 60, loginButton.bottom + 50, 120, 20)];
    threeloginLabel.text = @"使用社交账号登陆";
    threeloginLabel.font = [UIFont systemFontOfSize:14];
    threeloginLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:threeloginLabel];
    for (int i = 0; i < 2; i++) {
        UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(10 + threeloginLabel.right * i, loginButton.bottom + 60, threeloginLabel.left - 20, 1)];
        lineLabel.backgroundColor = [UIColor blackColor];
        [self.view addSubview:lineLabel];
    }
    NSArray *imgArray = @[@"weixin",@"qq",@"weibo"];
    UIColor *green = [UIColor greenColor];
    UIColor *blue = [UIColor blueColor];
    UIColor *red = [UIColor redColor];
    NSMutableArray *colorArray = [NSMutableArray arrayWithObjects:green,blue,red, nil];
    for (int i = 0; i < 3; i++) {
        UIButton *threeButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        threeButton.frame = CGRectMake(20 + (kScreenWidth / 2 - 60 ) * i, threeloginLabel.bottom + 50, 80, 80);
        threeButton.layer.masksToBounds = YES;
        threeButton.layer.cornerRadius = 40;
        threeButton.backgroundColor = colorArray[i];
        threeButton.tag = 100 + i;
        [threeButton setBackgroundImage:[UIImage imageNamed:imgArray[i]] forState:(UIControlStateNormal)];
        [threeButton addTarget:self action:@selector(threeButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
        [self.view addSubview:threeButton];
    }
   
}

// 第三方登陆

- (void)threeButtonClick:(UIButton *)sender{
    
    if (sender.tag == 100) {
        UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToWechatSession];
        snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
            
            if (response.responseCode == UMSResponseCodeSuccess) {
                
                UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary]valueForKey:UMShareToWechatSession];
                
                NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
                
            }
            
        });
    } else if (sender.tag == 101){
        
        UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToQQ];
        
        snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
            
            //          获取微博用户名、uid、token等
            
            if (response.responseCode == UMSResponseCodeSuccess) {
                
                UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToQQ];
                
                NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
                
            }});
    } else {
        
        UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
        
        snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
            
            if (response.responseCode == UMSResponseCodeSuccess) {
                
                UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToSina];
                // 这个地方可以获得姓名的信息
                NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
                
            }});
    }
}

// 登陆
- (void)loginButtonClick:(UIButton *)sender{
    NSString *email =  _userView.userText.text;
    NSString *newEmail = [email stringByReplacingOccurrencesOfString:@"@" withString:@"%40"];
    NSString *password = _passwordView.userText.text;
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"auth"] = @"";
    parDic[@"client"] = @"1";
    parDic[@"deviceid"] = @"24538A91-BDBB-4437-AEE0-0E24D8BF0D58";
    parDic[@"passwd"] = password;
    parDic[@"version"] = @"3.0.6";
    parDic[@"email"] = newEmail;
    [HWRequestManager requestWithUrl:@"http://api2.pianke.me/user/login" parmDic:parDic method:POST1 succeedWithData:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSDictionary *modelDic = dic[@"data"];
        HWPersonModel *model = [[HWPersonModel alloc] init];
        [model setValuesForKeysWithDictionary:modelDic];
        // 换登陆账号的时候 删除以前的信息
        [[HWFileMannager shareManager].db executeUpdate:@"DELETE FROM PersonList"];
        if (dic[@"data"][@"uname"] != nil) {
            // 登陆成功的时候保存联系人信息
            [[HWFileMannager shareManager].db executeUpdate:@"INSERT INTO PersonList (uID, coverimg, uname, icon, auth) VALUES (?, ?, ?, ?, ?)",model.uID, model.coverimg, model.uname, model.icon, model.auth];
            [[HWFileMannager shareManager] isLogin:YES];
            [self.navigationController popViewControllerAnimated:YES];
        } else {
           // NSString *msg = dic[@"data"][@"msg"];
        }
    } failedWithError:^(NSError *connectionError) {
        
    }];
   

    
    
}

// 实现代理方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    UITextField *temp = (UITextField *)[self.view viewWithTag:textField.tag + 1];
    // 成为第一响应者
    [temp becomeFirstResponder];
    
    // 判断是不是最后一个 textField
    if (textField.tag == 101) {
        [textField resignFirstResponder];
    }
    
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
